﻿using System.Configuration;

namespace Compass.Wpf.ApiServices;
public interface IPreferenceService
{
    string? Get(string key, string? defaultValue = null);
    void Set(string key, string value);
}
public class PreferencesService:IPreferenceService
{
    public string? Get(string key, string? defaultValue=null)
    {
        try
        {
            var settingString = ConfigurationManager.AppSettings[key];
            return settingString;
        }
        catch (Exception)
        {
            return defaultValue;
        }
    }

    public void Set(string key, string value)
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        if (ConfigurationManager.AppSettings[key] != null)
        {
            config.AppSettings.Settings.Remove(key);
        }
        config.AppSettings.Settings.Add(key, value);
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
    }
}